package com.dhb.pattern.proxy.dynamicproxy.jdkproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 功能描述：
 * 创建人：citymoon
 * 创建日期：2019/5/11
 */
public class JdkProxy implements InvocationHandler {

    //目标对象引用
    private Object target;

    public JdkProxy(Object target) {
        this.target = target;
    }

    /**
     * //给目标对象生成代理对象
     * @return
     */
    public Object getProxyInstance(){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                                      target.getClass().getInterfaces(),
                                      this);
    }

    /**
     * 代理对象的执行方法
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object object = method.invoke(this.target, args);
        after();
        return object;
    }

    private void before(){
        System.out.println("自我介绍");
    }

    private void after(){
        System.out.println("感谢观众");
    }
}
